import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import eslintPlugin from 'vite-plugin-eslint'
import { visualizer } from 'rollup-plugin-visualizer'
import ViteRestart from 'vite-plugin-restart'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import { createStyleImportPlugin, VantResolve } from 'vite-plugin-style-import'
import AutoImport from 'unplugin-auto-import/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { createHtmlPlugin } from 'vite-plugin-html'
import legacyPlugin from '@vitejs/plugin-legacy'

// https://vite.dev/config/
export default ({ mode }) => defineConfig({
  mode: 'development',
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  plugins: [
    vue(),
    eslintPlugin(),
    visualizer(), // 打包分析插件
    ViteRestart({
      // 自动重启 vite 服务
      restart: ['vite.config.[jt]s', '.env.*'],
    }),
    Components({
      // 组件自动按需导入
      dirs: ['src/components'], // 目标文件夹
      extensions: ['vue', 'jsx'], // 文件类型
      dts: 'src/components.d.ts', // 输出文件，里面都是一些import的组件键值对
      resolvers: [AntDesignVueResolver({
        importStyle: false
      })], // ui库解析器，也可以自定义，需要安装相关UI库
    }),
    createStyleImportPlugin({ // 样式按需引入
      resolves: [VantResolve()]
    }),
    AutoImport({ // 插件 hooks 自动引入
      imports: ['vue', 'vue-router', 'pinia', '@vueuse/head'],
      dts: 'src/auto-import.d.ts'
    }),
    createSvgIconsPlugin({ // svg图标导入
      iconDirs: [path.resolve(process.cwd(), 'src/svg')],
      symbolId: 'icon-[dir]-[name]'
    }),
    createHtmlPlugin({
      minify: true,
      entry: '/src/main.ts', // 在这里写entry后，你将不需要在`index.html`内添加 script 标签
      inject: {
        data: {
          title: loadEnv(mode, process.cwd()).VITE_PROJECT_TITLE, // 查找.env.test文件里面的VITE_PROJECT_TITLE，请以VITE_标识开头
          injectScript: `<script src="/inject.js"></script>`
        }
      }
    }),
    legacyPlugin({
      targets: ['chrome 52'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime']
    })
  ],
  envDir: '/',
  server: {
    host: '127.0.0.1', // 指定服务器应该监听哪个 IP 地址
    port: 8081, // 指定开发服务器端口
    strictPort: true, // 若端口已被占用则会直接退出
    open: true, // 启动时自动在浏览器中打开应用程序
    proxy: { // 配置自定义代理规则
      '/api': {
        target: '',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    },
  }
})
